package com.hellobike.haxing.modules.pms.purchaseSend.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hellobike.haxing.common.annotation.AutoLog;
import com.hellobike.haxing.common.system.base.controller.BaseController;
import com.hellobike.haxing.common.system.query.QueryGenerator;
import com.hellobike.haxing.common.system.vo.LoginUser;
import com.hellobike.haxing.common.vo.Result;
import com.hellobike.haxing.modules.pms.purchaseSend.dto.TPurchaseSendDto;
import com.hellobike.haxing.modules.pms.purchaseSend.entity.TPurchasePrintSku;
import com.hellobike.haxing.modules.pms.purchaseSend.entity.TPurchaseSend;
import com.hellobike.haxing.modules.pms.purchaseSend.service.ITPurchasePrintSkuService;
import com.hellobike.haxing.modules.pms.purchaseSend.service.ITPurchaseSendService;
import com.hellobike.haxing.modules.purchase.entity.TPurchaseOrderDetail;
import com.hellobike.haxing.modules.purchase.enums.SendState;
import com.hellobike.haxing.modules.purchase.service.ITPurchaseOrderDetailService;
import com.hellobike.haxing.modules.supplier.entity.TSupplierInfo;
import com.hellobike.haxing.modules.supplier.service.ITSupplierInfoService;
import com.hellobike.haxing.modules.supplier.util.BeanUtils;
import com.hellobike.haxing.modules.supplier.util.Constant;
import com.hellobike.haxing.modules.wms.utils.ListUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: t_purchase_send
 * @Author: haxing-boot
 * @Date: 2020-02-17
 * @Version: V1.0
 */
@RestController
@RequestMapping("/purchase/tPurchaseSend")
@Slf4j
public class TPurchaseSendController extends BaseController<TPurchaseSend, ITPurchaseSendService> {
    @Autowired
    private ITPurchaseSendService tPurchaseSendService;
    @Autowired
    private ITPurchasePrintSkuService tPurchasePrintSkuService;
    @Autowired
    private ITSupplierInfoService tSupplierInfoService;

    @Autowired
    private ITPurchaseOrderDetailService tPurchaseOrderDetailService;

    /**
     * 分页列表查询
     *
     * @param tPurchaseSend
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "t_purchase_send-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(TPurchaseSend tPurchaseSend,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<TPurchaseSend> queryWrapper = QueryGenerator.initQueryWrapper(tPurchaseSend, req.getParameterMap());
        Long supplierId = getSupplierId();
        if (supplierId == null) {
            return Result.error("用户不存在");
        }
        queryWrapper.eq("supplier_id", supplierId);
        Page<TPurchaseSend> page = new Page<TPurchaseSend>(pageNo, pageSize);
        IPage<TPurchaseSend> pageList = tPurchaseSendService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    private Long getSupplierId() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (sysUser == null) {
            return null;
        }
        QueryWrapper<TSupplierInfo> tSupplierInfoQueryWrapper = new QueryWrapper<>();
        tSupplierInfoQueryWrapper.eq("mobile", sysUser.getPhone());
        TSupplierInfo tSupplierInfo = tSupplierInfoService.getOne(tSupplierInfoQueryWrapper);
        if (tSupplierInfo == null) {
            return null;
        }
        return tSupplierInfo.getId();
    }

    /**
     * 添加
     *
     * @param tPurchaseSend
     * @return
     */
    @AutoLog(value = "t_purchase_send-添加", operateType = 2)
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody TPurchaseSend tPurchaseSend) {
        tPurchaseSendService.save(tPurchaseSend);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param tPurchaseSend
     * @return
     */
    @AutoLog(value = "t_purchase_send-编辑", operateType = 3)
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody TPurchaseSend tPurchaseSend) {
        tPurchaseSendService.updateById(tPurchaseSend);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "t_purchase_send-删除", operateType = 4)
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) Long id) {
        tPurchaseSendService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "t_purchase_send-批量删除", operateType = 4)
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.tPurchaseSendService.removeByIds(Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) Long id) {
        TPurchaseSend tPurchaseSend = tPurchaseSendService.getById(id);
        if (tPurchaseSend == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(tPurchaseSend);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param tPurchaseSend
     */
    @AutoLog(value = "t_purchase_send-导出excel", operateType = 6)
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, TPurchaseSend tPurchaseSend) {
        QueryWrapper<TPurchasePrintSku> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("print_code", tPurchaseSend.getSendCode());
        queryWrapper.eq("type", Constant.PRINT_SEND);
        List<TPurchasePrintSku> tPurchasePrintSkus = tPurchasePrintSkuService.list(queryWrapper);
        QueryWrapper<TPurchaseOrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        orderDetailQueryWrapper.eq("parent_order_code", tPurchaseSend.getPurchaseCode());
        List<TPurchaseOrderDetail> tPurchaseOrderDetails = tPurchaseOrderDetailService.list(orderDetailQueryWrapper);
        List<TPurchaseSendDto> tPurchaseSendDtoList = new ArrayList<>();
        if (ListUtil.isNotEmpty(tPurchasePrintSkus) && ListUtil.isNotEmpty(tPurchaseOrderDetails)) {
            for (TPurchasePrintSku item : tPurchasePrintSkus) {
                for (TPurchaseOrderDetail tPurchaseOrderDetail : tPurchaseOrderDetails) {
                    if (tPurchaseOrderDetail.getSkuId().equals(item.getSkuId())) {
                        TPurchaseSendDto tPurchaseSendDto = new TPurchaseSendDto();
                        BeanUtils.copyProperties(tPurchaseSend, tPurchaseSendDto);
                        BeanUtils.copyProperties(item, tPurchaseSendDto);
                        try {
                            tPurchaseSendDto.setSendState(SendState.getName(tPurchaseSend.getState()));
                        } catch (Exception ex) {
                            log.error("状态异常=={}", JSON.toJSONString(tPurchaseSendDto));
                            tPurchaseSendDto.setSendState(SendState.SEND_STATE_0.getName());
                        }
                        tPurchaseSendDto.setSkuTotalVolume(tPurchaseOrderDetail.getPurchaseVolume());
                        tPurchaseSendDtoList.add(tPurchaseSendDto);
                    }
                }
            }
        }
        return newExportXls(tPurchaseSendDtoList, "供应商发货单");
    }


    /**
     * 导出excel
     */
    protected ModelAndView newExportXls(List<TPurchaseSendDto> exportList, String title) {
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        if (ListUtil.isNotEmpty(exportList)) {
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            mv.addObject(NormalExcelConstants.FILE_NAME, title);
            mv.addObject(NormalExcelConstants.CLASS, TPurchaseSendDto.class);
            mv.addObject(NormalExcelConstants.PARAMS, new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title));
            mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        }
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @AutoLog(value = "t_purchase_send-导入excel", operateType = 5)
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, TPurchaseSend.class);
    }

}
